﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using BrnMall.Core;
using Newtonsoft.Json;
using Ship.DaDa;

namespace BrmMall.Ship.DaDa
{
    /// <summary>
    /// 达达配送SDK助手类
    /// </summary>
    public class DaDaHelper
    {

        #region 订单处理
        /// <summary>
        /// 查询配送运费
        /// </summary>
        /// <param name="order"></param>
        /// <param name="cityCode">城市代码(如：深圳市: 0755)</param>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <returns></returns>
        public static JsonModel<QueryFeeModel> QueryFee(OrderInfo order, string cityCode, double longitude, double latitude)
        {
            var param = GetOrderInfo(order, cityCode, latitude, longitude);
            var jsonHtml = SDK.QueryFee(param);
            var model = JsonConvert.DeserializeObject<JsonModel<QueryFeeModel>>(jsonHtml);

            if (IsSuccess(model))
            {
                Trace.TraceInformation(string.Format("DataHelper.QueryFee() 参数:{0} 返回:{1}", Function.ToJson(param), jsonHtml));
                return model;
            }
            else
            {
                Trace.TraceError(string.Format("DataHelper.QueryFee() 失败 参数:{0} 返回:{1}", Function.ToJson(param), jsonHtml));
                return GetErrorModel(new QueryFeeModel());
            }
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="cityCode">城市代码(如：深圳市: 0755)</param>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <returns></returns>
        public static JsonModel<AddOrderModel> AddOrder(OrderInfo order, string cityCode, double latitude, double longitude)
        {
            var param = GetOrderInfo(order, cityCode, longitude, latitude);
            var jsonHtml = SDK.AddOrder(param);
            var model = JsonConvert.DeserializeObject<JsonModel<AddOrderModel>>(jsonHtml);
            if (IsSuccess(model))
            {
                Trace.TraceInformation(string.Format("DataHelper.AddOrder() 参数:{0} 返回:{1}", Function.ToJson(param), jsonHtml));
                return model;
            }
            else
            {
                Trace.TraceError(string.Format("DataHelper.AddOrder() 达达配送订单失败, 参数:{0} 返回:{1}", Function.ToJson(param), jsonHtml));
                return GetErrorModel(new AddOrderModel());
            }
        }

        /// <summary>
        /// 查询订单及骑手的位置
        /// </summary>
        /// <param name="osn">订单号</param>
        /// <returns></returns>
        public static GetOrderModel GetOrder(string osn)
        {
            var jsonHtml = SDK.GetOrder(osn);
            var model = JsonConvert.DeserializeObject<JsonModel<GetOrderModel>>(jsonHtml);
            if (IsSuccess(model))
                return model.Result;
            return null;
        }

        /// <summary>
        /// 取消订单，返回违约金
        /// </summary>
        /// <param name="osn"></param>
        /// <param name="cancel_reason_id"></param>
        /// <param name="cancel_reason"></param>
        /// <returns></returns>
        public static JsonModel<CacelOrderModel> CacelOrder(string osn, int cancel_reason_id, string cancel_reason = "")
        {
            var jsonHtml = SDK.CacelOrder(osn, cancel_reason_id, cancel_reason);
            return JsonConvert.DeserializeObject<JsonModel<CacelOrderModel>>(jsonHtml);
        }

        /// <summary>
        /// 获取取消订单理由ID
        /// </summary>
        /// <returns></returns>
        public static List<CacelReasonModel> GetCacelReason()
        {
            var jsonHtml = SDK.GetCacelReasons();
            var jsonModel = JsonConvert.DeserializeObject<JsonModel<List<CacelReasonModel>>>(jsonHtml);
            return IsSuccess(jsonModel) ? jsonModel.Result : null;
        }
        #endregion

        #region 门店管理

        /// <summary>
        /// 创建门店
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static AddShopModel AddShop(StoreInfo info, string city_name, string longitude, string latitude)
        {
            var list = new List<Dictionary<string, object>>();
            var param = new Dictionary<string, object>();

            //门店编码,可自定义,但必须唯一;若不填写,则系统自动生成
            param.Add("origin_shop_id", info.StoreId);
            //门店名称
            param.Add("station_name", info.Name);
            //城市名称(如,上海)
            param.Add("city_name", city_name);
            //区域名称(如,浦东新区)
            param.Add("area_name", "福田区");
            //门店地址
            param.Add("station_address", info.Address);
            //门店经度
            param.Add("lng", longitude);
            //门店纬度
            param.Add("lat", latitude);
            //联系人姓名
            param.Add("contact_name", info.Name);
            //电话
            param.Add("phone", string.IsNullOrEmpty(info.Phone) ? info.Mobile : info.Phone);

            //门店业务
            param.Add("business", "1");
            list.Add(param);

            var jsonHtml = SDK.AddShhop(list);
            var model = JsonConvert.DeserializeObject<JsonModel<AddShopModel>>(jsonHtml);

            return model != null ? model.Result : null;
        }

        /// <summary>
        /// 获取门店
        /// </summary>
        /// <param name="origin_shop_id"></param>
        /// <returns></returns>
        public static ShopModel GetShop(string origin_shop_id)
        {
            var jsonHtml = SDK.GetShop(origin_shop_id);
            var model = JsonConvert.DeserializeObject<JsonModel<ShopModel>>(jsonHtml);
            return model != null ? model.Result : new ShopModel(origin_shop_id);
        }

        #endregion

        #region 余额管理
        /// <summary>
        /// 余额查询
        /// </summary>
        /// <param name="category">查询运费账户类型（1：运费账户；2：红包账户，3：所有），默认查询运费账户余额</param>
        public static BalanceModel GetBalance(int category)
        {
            var jsonHtml = SDK.GetBalance(category);
            var model = JsonConvert.DeserializeObject<JsonModel<BalanceModel>>(jsonHtml);
            return model != null ? model.Result : new BalanceModel();
        }

        #endregion

        #region 其他功能
        
        /// <summary>
        /// 返回城市代码
        /// </summary>
        /// <returns></returns>
        public static CityCodeModel GetCityCode(string cityName)
        {
            var param = new Dictionary<string, object>();
            var jsonHtml = SDK.GetCityCode(param);
            var model = JsonConvert.DeserializeObject<JsonModel<List<CityCodeModel>>>(jsonHtml);
            if (model != null && model.Result != null)
            {
                return model.Result.Find(x => (cityName.Contains(x.CityName) || x.CityName.Contains(cityName)));
            }
            return null;
        }

        /// <summary>
        /// 返回结果检测
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsSuccess<T>(JsonModel<T> t)
        {
            if (t != null && t.Code == 0)
                return true;
            return false;
        }

        public static string ToJson(object obj)
        {
            return Function.ToJson(obj);
        }

        /// <summary>
        /// 格式化订单状态
        /// </summary>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        public static string FormatOrderState(int statusCode)
        {
            string statusName = "未知";
            switch (statusCode)
            {
                case 1: statusName = "待接单"; break;
                case 2: statusName = "待取货"; break;
                case 3: statusName = "配送中"; break;
                case 4: statusName = "已完成"; break;
                case 5: statusName = "已取消"; break;
                case 7: statusName = "已过期"; break;
                case 8: statusName = "指派单"; break;
                case 9: statusName = " 妥投异常之物品返回中"; break;
                case 10: statusName = "妥投异常之物品返回完成"; break;
                case 1000: statusName = "系统故障订单发布失败"; break;
            }
            return statusName;
        }

        #endregion

        #region 私有方法

        static JsonModel<T> GetErrorModel<T>(T t)
        {
            return new JsonModel<T>() { Code = 500, Result = t, Status = "fail", Msg = "json转换错误" };
        }

        static Dictionary<string, object> GetOrderInfo(OrderInfo order, string city_code, double receiver_lat, double receiver_lng)
        {
            var param = new Dictionary<string, object>();

            //门店编号，门店创建后可在门店列表和单页查看
            param.Add("shop_no", order.StoreId);
            //第三方订单ID
            param.Add("origin_id", order.OSN);
            //订单金额
            param.Add("cargo_price", order.OrderAmount);
            //收货人姓名
            param.Add("receiver_name", order.Consignee);
            //收货人地址
            param.Add("receiver_address", order.Address);
            //收货人手机号（手机号和座机号必填一项）
            param.Add("receiver_phone", order.Mobile);

            //订单所在城市的code
            param.Add("city_code", city_code);
            //收货人地址维度（高德坐标系）
            param.Add("receiver_lat", receiver_lat);
            //收货人地址经度（高德坐标系）
            param.Add("receiver_lng", receiver_lng);
            //回调URL
            param.Add("callback", Config.api_callback);
            //是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
            param.Add("is_prepay", 0);
            return param;
        }

        #endregion
    }
}
